package cn.wolfcode.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.wolfcode.domain.Appointment;
import cn.wolfcode.domain.Consumption;
import cn.wolfcode.enums.ConsumptionStatusEnum;
import cn.wolfcode.mapper.AppointmentMapper;
import cn.wolfcode.mapper.ConsumptionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IConsumptionService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ConsumptionServiceImpl implements IConsumptionService {

    @Autowired
    private ConsumptionMapper consumptionMapper;

    @Autowired
    private AppointmentMapper appointmentMapper;


    @Override
    public void save(Consumption consumption) {
        consumptionMapper.insert(consumption);
    }

    @Override
    public void delete(Long id) {
        consumptionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Consumption consumption) {
        consumptionMapper.updateByPrimaryKey(consumption);
    }

    @Override
    public Consumption get(Long id) {
        return consumptionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Consumption> listAll() {
        return consumptionMapper.selectAll();
    }

    @Override
    public PageInfo<Consumption> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),"status,pay_time");
        List<Consumption> consumptions = consumptionMapper.selectForList(qo);
        return new PageInfo<Consumption>(consumptions);
    }


    @Override
    public Consumption save(String appointmentAno) {
        //修改预约单状态为消费中
        Appointment appointment = appointmentMapper.selectByAno(appointmentAno);
        appointmentMapper.changeStatus(appointment.getId(),2);
        //创建结算单对象
        Consumption consumption = new Consumption();
        //把预约单的信息设置到结算单中
        consumption.setStatus(ConsumptionStatusEnum.CONSUME.getValue());
        consumption.setCustomerName(appointment.getContactName());
        consumption.setCustomerTel(appointment.getContactTel());
        //把预约单的流水号设置景区
        consumption.setAppointmentAno(appointmentAno);
        Date date = new Date();
        //进店时间
        consumption.setCheckinTime(date);
        //获取预约单的门店id并设置进去(mapper查询直接设置id即可)
        consumption.setBusiness(appointment.getBusiness());
        //创建时间
        consumption.setCreateTime(date);
        //创建人,即正在登录的员工
        consumption.setCreateUser(UserContext.getCurrentUser());
        //生成结算单流水号
        String date1 = DateUtil.format(date, "yyyyMMddHHmmss");
        String data2 = RandomUtil.randomNumbers(5);
        consumption.setCno(date1+data2);

        //保存到数据库
        consumptionMapper.insert(consumption);
        return consumption;
    }
}
